﻿//需要一个棋盘（二维数组）
//需要一个随机布雷函数
//需要一个能计算周边有几个雷的函数
//需要一个能判断如果排查位置不是雷，周围也没有雷，可以展开周围的⼀⽚函数
void DisplayBoard(char** board, int row, int col) {
    printf("\n   ");
    for (int i = 1; i <= col; i++) printf("%-2d", i);
    printf("\n");

    for (int i = 0; i < row; i++) {
        printf("%-2d ", i + 1);
        for (int j = 0; j < col; j++) {
            printf("%c ", board[i][j]);
        }
        printf("\n");
    }
}

void Installmines(char** arr, int row, int col, int count) {
    while (count > 0) {
        int x = rand() % row;
        int y = rand() % col;
        if (arr[x][y] == '0') {
            arr[x][y] = '1';
            count--;
        }
    }
}
void Expand(char** mine, char** show, int x, int y, int row, int col, int* win) {
    // 检查边界条件
    if (x < 0 || x >= row || y < 0 || y >= col) return;
    // 如果已经展开过则返回
    if (show[x][y] != '*') return;

    // 计算周围雷数
    int count = GetMineCount(mine, x, y, row, col);
    if (count > 0) {
        show[x][y] = count + '0';
        (*win)++;
        return;
    }

    // 如果是0则标记为空格并展开周围
    show[x][y] = ' ';
    (*win)++;

    // 递归展开周围8个方向
    for (int dx = -1; dx <= 1; dx++) {
        for (int dy = -1; dy <= 1; dy++) {
            if (dx == 0 && dy == 0) continue; // 跳过自身
            Expand(mine, show, x + dx, y + dy, row, col, win);
        }
    }
}
int GetMineCount(char** arr, int x, int y, int row, int col) {
    int count = 0;
    for (int i = x - 1; i <= x + 1; i++) {
        for (int j = y - 1; j <= y + 1; j++) {
            if (i >= 0 && i < row && j >= 0 && j < col && !(i == x && j == y)) {
                count += arr[i][j] - '0';
            }
        }
    }
    return count;
}

void FindMine(char** mine, char** show, int row, int col, int total_mines) {
    int win = 0;
    while (win < row * col - total_mines) {
        int x, y;
        printf("输入坐标 (行 列): ");
        scanf("%d %d", &x, &y);

        if (x < 1 || x > row || y < 1 || y > col) {
            printf("无效坐标!\n");
            continue;
        }

        x--; y--; // 转换为0-based索引

        if (mine[x][y] == '1') {
            printf("游戏结束! 触雷了!\n");
            DisplayBoard(mine, row, col);
            return;
        }

        // 使用新的展开函数
        if (show[x][y] == '*') {
            Expand(mine, show, x, y, row, col, &win);
        }

        DisplayBoard(show, row, col);
    }
    printf("恭喜，扫雷成功!\n");
    DisplayBoard(mine, row, col);
}
void FreeBoard(char** board, int row) {
    for (int i = 0; i < row; i++) free(board[i]);
    free(board);
}

